package org.keyroy.mapEditor.ui.views;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.graphics.Transform;
import org.eclipse.swt.widgets.Composite;
import org.keyroy.map.core.Map;
import org.keyroy.map.render.SWTMapRenderEngine;

public class MapThumbnailView extends Composite {
	private Map map;
	private SWTMapRenderEngine engine = new SWTMapRenderEngine();
	private Image image;

	/**
	 * Create the composite.
	 * 
	 * @param parent
	 * @param style
	 */
	public MapThumbnailView(Composite parent) {
		super(parent, SWT.NONE);
		addControlListener(new ControlListener() {

			@Override
			public void controlResized(ControlEvent e) {
				reset();
			}

			@Override
			public void controlMoved(ControlEvent e) {

			}
		});

		addPaintListener(new PaintListener() {
			@Override
			public void paintControl(PaintEvent e) {
				if (image != null) {
					Point point = getSize();
					Rectangle rectangle = image.getBounds();
					e.gc.drawImage(image, (point.x - rectangle.width) / 2, (point.y - rectangle.height) / 2);
				}
			}
		});
	}

	public void setMap(Map map) {
		this.map = map;
		engine.setMap(map);
		reset();
	}

	public final void reset() {
		Point point = getSize();

		try {
			if (map == null) {
				image = null;
				return;
			}

			if (point.x > 0 && point.y > 0) {
				int mWidth = map.getColumns() * map.getGridWidth();
				int mHeight = map.getRows() * map.getGridHeight();

				java.awt.Rectangle screen = new java.awt.Rectangle();
				screen.setSize(mWidth, mHeight);

				float scaleW = (float) (point.x) / (float) mWidth;
				float scaleH = (float) (point.y) / (float) mHeight;

				float scale = Math.min(scaleW, scaleH);

				int imgWidth = (int) (mWidth * scale);
				int imgHeight = (int) (mHeight * scale);
				if (imgWidth > 0 && imgHeight > 0) {
					image = new Image(null, imgWidth, imgHeight);
					GC gc = new GC(image);
					Transform swtTransform = new Transform(gc.getDevice());
					gc.getTransform(swtTransform);
					swtTransform.scale((float) scale, (float) scale);
					gc.setTransform(swtTransform);
					engine.drawTiles(gc, null);
					engine.drawTilesOverlay(gc, null);
					engine.drawPointObject(gc, (java.awt.Rectangle)null);
					swtTransform.dispose();
					gc.dispose();
					redraw();

				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		redraw();
	}

}
